package com.mangowang.module.main.web.ui;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import com.mangowang.lib.common.R;
import com.mangowang.lib.common.base.BaseFragment;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.util.LogUtil;
import com.mangowang.lib.common.util.ValidateUtils;
import com.mangowang.module.main.web.inteface.JavaScriptInterface;
import com.mangowang.module.main.web.manager.MyChromeClient;
import com.mangowang.module.main.web.manager.WebViewClientUtil;


/**
 * Created by Frank on 2018/1/9.
 */

public class WebViewFragment extends BaseFragment implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {


    private Handler jsInterfaceHandler;
    private String url;
    WebView webView;
    public static final int JUMPTO = 0x8fe;
    public static WebViewFragment newInstance(String url) {
      WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_web_view;
    }

    @Override
    protected void initView() {
        url = getArguments().getString("url");
        jsInterfaceHandler = new JsInterfaceHandler(this.getActivity(), webView,null);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(getActivity(), this));
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.setWebChromeClient(new MyChromeClient(getActivity(), this, this, webView, null));
        webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        if (UserHelper.isLogin()) {
            syncCookie(getActivityContext(), url);   //同步cookie
        }
        loadUrl();
    }

    @Override
    protected void init() {

    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if (UserHelper.isLogin()) {
            if (url.contains("?")) {
                newUrl = url + "&key=" + UserHelper.getCurrentToken();
            } else {
                newUrl = url + "?key=" + UserHelper.getCurrentToken();
            }
        } else {
            newUrl = url;
        }
        webView.loadUrl(newUrl);
        LogUtil.e("frank", "WebViewFragment网页请求地址：" + newUrl);
    }


    public void reLoad()
    {
        if (url.contains("statistics"))
        {
            webView.reload();
        }
    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("frank", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Frank: webView.syncCookie failed", e.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        webView  =   rootView.findViewById(R.id.webView);
        return rootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void loadFinished(String title, boolean isError) {

    }



    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        Log.e("onProgressChanged", newProgress + "\n");
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {

    }


    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private Activity context;
        private WebView webViews;
        private RelativeLayout contentLayout;
        private RelativeLayout totalBgLayout;

        public JsInterfaceHandler(Activity activity, WebView webViews, RelativeLayout contentLayout) {
            this.context = activity;
            this.webViews = webViews;
            this.contentLayout = contentLayout;
        }


        @Override
        public void handleMessage(Message msg) {
            if (ValidateUtils.isValidate(msg.obj)) {
                switch (msg.what) {
                    case JUMPTO:
                        WebViewActivity.startActivity(context, msg.obj.toString(), false);
                        break;

                }

            }

        }
    }

}
